import axios, { InternalAxiosRequestConfig, AxiosResponse } from "axios"
import { ElMessage } from 'element-plus'

// 创建 axios 实例
const request = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,
  timeout: 10000,
  headers: { "Content-Type": "application/json;charset=utf-8" },
});

// 请求拦截器
request.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const token = window.sessionStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error: any) => {
    return Promise.reject(error)
  }
);

// 响应拦截器
request.interceptors.response.use(
  (response: AxiosResponse) => {
    const data = response.data;
    if (data.code === 200) {
      return response.data;
    }
    ElMessage.error(data.msg || "系统出错");
    return Promise.reject(new Error(data.msg || "Error"));
  },
  (error: any) => {
    if (error.response.data) {
      ElMessage.error(error.response.data.msg || "系统出错");
    }
    return Promise.reject(error.message);
  }
);

// 导出 axios 实例
export default request;

